const express = require('express')
const userRouter = express.Router()
const userModel = require("../modules/user_tab")
const userRelationModel = require("../modules/user_relation_tab")
const { body, validationResult } = require('express-validator')
const { raw } = require('body-parser')
const JWT = require('../utils/jwtToken')
const Sequelize = require('sequelize')
const Op = Sequelize.Op
const axios = require('axios')
// 用户注册
userRouter.post('/register', async (req, res, next) => {
  try {
    const users = await userModel.findAll({ raw: true })
    let user_id = users.length > 0 ? users.sort((a, b) => b.user_id - a.user_id)[0].user_id + 1 : 1
    const { password, nickname, create_time } = req.query;
    const result = await userModel.create({ password, nickname, user_id, create_time });
    res.json({
      code: 1,
      msg: '请求成功',
      data: result
    });
  } catch (err) {
    next(err);
  }
});

//用户登录
userRouter.post('/login', async (req, res, next) => {
  try {
    const { nickname, password } = req.query
    const user = await userModel.findOne({ where: { nickname, password, is_delete: 0 } });
    if (!user) {
      return res.status(401).json({
        code: 0,
        msg: '请检查用户名和密码是否正确',
      });
    }
    res.json({
      code: 1,
      msg: '请求成功',
      data: user
    });
  } catch (err) {
    next(err);
  }
});

//微信一键登录
userRouter.post('/login/weixin', async (req, res, next) => {
  try {
    const { nickname, avatar, code, create_time } = req.query
    //获取openid
    const appID = 'wx3c06d388740d11e3';
    const appSecret = '533da9e49dab14be0b59945a78510d28';
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appID}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`
    const result1 = await axios.get(url)
    const { openid } = result1.data
    const user = await userModel.findOne({
      raw: true,
      where: {
        is_delete: 0,
        openid
      }
    })
    if (user) {
      return res.json({
        code: 1,
        msg: '请求成功',
        data: user
      })
    } else {
      const users = await userModel.findAll({ raw: true })
      let user_id = users.length > 0 ? users.sort((a, b) => b.user_id - a.user_id)[0].user_id + 1 : 1
      // 下载头像图片
      const response = await axios.get(avatar, {
        responseType: 'arraybuffer',
      })
      // 将图片数据转换为Base64编码字符串
      const base64String = Buffer.from(response.data, 'binary').toString('base64');
      // 构建DataURL
      const imageUrl = `data:image/png;base64,${base64String}`; // 是PNG格式
      const result = await userModel.create({
        nickname,
        user_id,
        create_time,
        avatar: imageUrl,
        openid
      });
      res.json({
        code: 1,
        msg: '请求成功',
        data: result
      });
    }
  } catch (err) {
    next(err);
  }
})

//修改微信头像
userRouter.post('/update/avatar', async (req, res, next) => {
  try {
    const { avatar, user_id } = req.body
    //判断用户是否存在
    const user = await userModel.findOne({ where: { user_id, is_delete: 0 } });
    if (!user) {
      return res.json({
        code: 0,
        msg: '查询失败',
      });
    }
    const result = await user.update({
        avatar
    });
    res.json({
      code: 1,
      msg: '请求成功',
      data: result
    })


  } catch (err) {
    next(err)
  }
})

//获取所有用户信息
userRouter.get('/search/all', async (req, res, next) => {
  try {
    const result = await userModel.findAll({
      raw: true,
      where: {
        is_delete: 0
      }
    })
    res.json({
      code: 1,
      msg: result
    })
  } catch (err) {
    next(err)
  }
})

//获取用户男女比例
userRouter.get('/search/genders', async (req, res, next) => {
  try {

    const user = await userModel.findAll({
      raw: true,
      where: {
        is_delete: 0
      }
    })
    const woman = user.filter((item) => item.gender == 1 && item.role == 0 && item.is_delete == 0)
    const man = user.filter((item) => item.gender == 2 && item.role == 0 && item.is_delete == 0)
    const unkown = user.filter((item) => item.gender == null && item.role == 0 && item.is_delete == 0)
    res.json({
      code: 1,
      meg: '请求成功',
      data: [
        {
          name: '男',
          value: man.length
        },
        {
          name: '女',
          value: woman.length
        },
        {
          name: '未知',
          value: unkown.length
        }
      ]
    })
  } catch (err) {
    next(err)
  }
})

// 根据id删除用户信息,假删除
userRouter.post('/delete', async (req, res, next) => {
  try {
    const { user_id } = req.query;
    const user = await userModel.findOne({ where: { user_id, is_delete: 0 } });
    if (!user) {
      res.json({
        code: 0,
        msg: '该用户不存在'
      });
      return
    }
    await user.update({ is_delete: 1 });
    res.json({
      code: 1,
      msg: '请求成功',
    });
  } catch (err) {
    next(err);
  }
});

// 根据id查询用户信息
userRouter.get('/search/id', async (req, res, next) => {
  try {
    const { user_id } = req.query;
    const user = await userModel.findOne({ where: { user_id: Number(user_id), is_delete: 0 }, raw: true });
    res.json({
      code: 1,
      msg: '请求成功',
      data: user
    });
  } catch (err) {
    next(err);
  }
})

// 根据id更新用户信息
userRouter.post('/update', async (req, res, next) => {
  try {
    const { user_id, nickname, age, password, realname, email, phone, gender, address, avatar, is_member, occupation, introduction } = req.query;
    const where = {
      is_delete: 0
    }
    //处理拿到的参数
    for (let key in req.query) {
      if (req.query[key]) {
        where[key] = req.query[key]
      }
    }
    //判断用户是否存在
    const user = await userModel.findOne({ where: { user_id, is_delete: 0 } });
    if (!user) {
      return res.json({
        code: 0,
        msg: '查询失败',
      });
    }
    const result = await user.update(where);
    res.json({
      code: 1,
      msg: '更新成功',
      data: result
    });
  } catch (err) {
    next(err);
  }
})
//获取近七天的用户注册量
userRouter.get('/search/seven', async (req, res, next) => {
  try {
    const lastWeekDates = [];
    const nums = []
    // 构建原始的 SQL 片段，用于比较日期是否相同
    const now = new Date()
    for (var i = 6; i >= 0; i--) {
      var tempDate = new Date(now);
      tempDate.setDate(now.getDate() - i);
      lastWeekDates.push(tempDate.toISOString().split('T')[0]);
    }

    for (let i = 0; i < lastWeekDates.length; i++) {
      const rawSqlFragment = Sequelize.literal(`date_format(create_time,'%Y-%m-%d') = '${lastWeekDates[i]}'`);
      const users = await userModel.findAll({
        raw: true,
        where: {
          [Op.and]: [
            rawSqlFragment,
            is_delete = 0
          ]
        }
      })
      if (!users) {
        nums.push(0)
      }
      nums.push(users.length)
    }
    res.json({
      code: 1,
      msg: '请求成功',
      data: {
        date: lastWeekDates,
        num: nums
      }
    })
  } catch (err) {
    next(err)
  }
})

//分页和模糊查询以及按时间排序
userRouter.get('/search', async (req, res, next) => {

  try {
    const page = parseInt(req.query.pageNum) || 1;
    const pageSize = parseInt(req.query.pageSize) || 10;
    const offset = (page - 1) * pageSize;
    const nickname = req.query.name
    const sortFieldName = req.query.sortFieldName
    const sortOrder = req.query.sortOrder || 'DESC'
    const order = []
    const where = {
      is_delete: 0
    }
    order.push([sortFieldName, sortOrder])
    if (nickname) {
      where.nickname = {
        [Op.like]: `%${nickname}%`
      }
    }
    //获取toatl
    const userLen = await userModel.findAll({
      raw: true,
      where
    })
    const result = await userModel.findAll({
      raw: true,
      offset,
      limit: pageSize,
      order,
      where
    });
    res.json({
      code: 1,
      msg: '请求成功',
      data: result,
      page,
      pageSize,
      total: userLen.length
    });
  } catch (err) {
    next(err);
  }
})
//用户管理，新增用户
userRouter.post('/add/one', async (req, res, next) => {
  try {
    const users = await userModel.findAll({ raw: true })
    let user_id = users.sort((a, b) => b.user_id - a.user_id)[0].user_id + 1
    const where = {
      is_delete: 0,
      user_id
    }
    //处理拿到的参数
    for (let key in req.query) {
      if (req.query[key]) {
        where[key] = req.query[key]
      }
    }
    
    const result = await userModel.create(where)

    res.json({
      code: 1,
      msg: '请求成功',
      data: result
    })
  } catch (err) {
    next(err)
  }
})
//批量删除，假删除
userRouter.post('/delete/amount', async (req, res, next) => {
  try {
    const { users } = req.query;
    users.forEach(async (item) => {
      const user = await userModel.findOne({ where: { user_id: item.user_id, is_delete: 0 } });
      await user.update({ is_delete: 1 });
    })
    res.json({
      code: 1,
      msg: '请求成功'
    })
  } catch (err) {
    next(err);
  }
})

//获取关注的人
userRouter.get('/focus/list', async (req, res, next) => {
  try {
    const { user_id } = req.query
    if (!user_id) {
      return res.status(400).json({ error: '缺少用户 ID' });
    }
    // 查询所有关注的人的个人信息
    const result = await userRelationModel.findAll({
      where: { user_id, is_delete: 0 },
    })
    res.json({
      code: 1,
      msg: '请求成功',
      data: result
    })
  } catch (err) {
    next(err)
  }
})
//根据user_id和friend_id取消关注,假删除
userRouter.post("/unfocus", async (req, res, next) => {
  try {
    const { user_id, friend_id } = req.query
    const follow = await userRelationModel.findOne({ where: { user_id, is_delete: 0, friend_id } });
    if (!follow) {
      return res.json({
        code: 0,
        msg: '该记录不存在'
      });
    }
    await follow.update({ is_delete: 1 });
    res.json({
      code: 1,
      msg: '请求成功',
    });
  } catch (err) {
    next(err)
  }
})
//点击关注
userRouter.post("/focus", async (req, res, next) => {
  try {
    const { user_id, friend_id } = req.query
    const follow = await userRelationModel.findOne({ where: { user_id, is_delete: 1, friend_id } });
    if (follow) {
      await follow.update({ is_delete: 0 });
      return res.json({
        code: 1,
        msg: '请求成功',
        data:follow
      })
    } else {
      const focs = await userRelationModel.findAll({ raw: true })
      let user_rela_id = focs.length > 0 ? users.sort((a, b) => b.user_id - a.user_id)[0].user_id + 1 : 1
    const result = await userRelationModel.create({ user_id, user_rela_id, friend_id, is_delete:0 });
      return res.json({
        code: 1,
        msg: '请求成功',
        data:result
      });
    }
  } catch (err) {
    next(err)
  }
})
//随机获取用户
userRouter.get('/random',async(req,res,next) => {
  try{
    const users = await userModel.findAll({ raw: true ,
      where:{
        is_delete:0,
        role:0
      }
    })
    const randomIndex = Math.floor(Math.random() * users.length)
    const user = users[randomIndex]
    res.json({
      code:1,
      msg:'请求成功',
      data:user
    })
  }catch(err){
    next(err)
  }
})

// 错误处理中间件
userRouter.use((err, req, res, next) => {

  res.status(500).json({
    code: 0,
    msg: '服务器内部错误',
  });
});
module.exports = userRouter